﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core.Lister;

namespace COFE.Core.Filter
{
    [EntryFilter("root")]
    public class RootEntryFilter : EntryFilterBase
    {
        public RootEntryFilter(string parsePath, string id = "root")
            : base(parsePath, id)
        {
            SupportedMatchType = MatchType.MatchSubEntry | MatchType.MatchThisEntry;
            _rootDirectory = COFEShared.CurrentUserProfile.TryParsePath(
                   Value, Profile.EntryConstructionFlags.Default)
                   as IDirectoryInfo;
            if (_rootDirectory == null)
                throw new System.IO.FileNotFoundException(parsePath);
        }

        public RootEntryFilter(IDirectoryInfo rootDirectory, string id = "root")
            : base(rootDirectory.ParseName, id)
        {
            SupportedMatchType = MatchType.MatchSubEntry | MatchType.MatchThisEntry;
            _rootDirectory = rootDirectory;
        }

        public override MatchType matches(IInternalFileSystemInfoExA entry,
            params IOptionFilter[] options)
        {
            MatchType retVal = MatchType.None;
            string entryParseName = entry.ParseName;
            bool sameRoot = 
                Value.Equals(ProfileRootDirectoryLister
                .ProfileRootParsablePath) || //Root directory 
                entryParseName.StartsWith(Value,
                    StringComparison.InvariantCultureIgnoreCase);
            bool sameDir = sameRoot &&
                entryParseName.Equals(Value,
                StringComparison.InvariantCultureIgnoreCase);
            bool isFBFS = entry is IDirectoryInfo && 
                (entry as IInternalDirectoryInfoExA).IsFileBasedFS;

            switch (options.GetSearchOption())
            {
                case SearchOptionEx.AllDirectories:
                    if (sameRoot)
                        retVal |= MatchType.MatchSubEntry;                            
                    break;
                case SearchOptionEx.AllDirectoriesAndFileBasedFS:
                    if (sameRoot || isFBFS)
                        retVal |= MatchType.MatchSubEntry;                            
                    break;
            }
            
            return retVal | MatchType.MatchThisEntry; 
        }

        private IDirectoryInfo _rootDirectory;

        public IDirectoryInfo Directory { get { return _rootDirectory; } }

    }
}
